{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a53fde7e-f24f-4cb0-9962-9ed075790628",
   "metadata": {},
   "outputs": [],
   "source": [
    "from gs_quant.session import GsSession\n",
    "\n",
    "GsSession.use()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6a9bc9fb-3914-49fc-b3cf-4e59d22fd8a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "from gs_quant.instrument import OptionStyle\n",
    "from gs_quant.backtests.strategy import Strategy\n",
    "from gs_quant.backtests.triggers import *\n",
    "from gs_quant.backtests.actions import *\n",
    "from gs_quant.backtests.equity_vol_engine import *\n",
    "from datetime import datetime, date\n",
    "\n",
    "import gs_quant.risk as risk"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a6175aa-bd47-4cd3-bead-dcebe4f5ea8d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize session\n",
    "from gs_quant.session import GsSession\n",
    "\n",
    "GsSession.use(client_id=None, client_secret=None, scopes=('run_analytics',))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5e2c6435-b2a0-4824-ae5c-4d4ef0f42ee4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define backtest dates\n",
    "start_date = date(2024, 4, 1)\n",
    "end_date = datetime.today().date()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "62435b59-ec26-4d5b-9b74-fd72396a468d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define instruments for strategy\n",
    "# Portfolio of two eq options\n",
    "call = EqOption(\n",
    "    '.STOXX50E',\n",
    "    expiration_date='1m',\n",
    "    strike_price='ATM',\n",
    "    option_type=OptionType.Call,\n",
    "    option_style=OptionStyle.European,\n",
    "    name='call',\n",
    ")\n",
    "put = EqOption(\n",
    "    '.STOXX50E',\n",
    "    expiration_date='1m',\n",
    "    strike_price='ATM',\n",
    "    option_type=OptionType.Put,\n",
    "    option_style=OptionStyle.European,\n",
    "    name='put',\n",
    ")\n",
    "portfolio = Portfolio(name='portfolio', priceables=[call, put])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea1412f0-055e-4954-9d05-527e93018181",
   "metadata": {},
   "source": [
    "### Entering a position monthly"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "adb4fc9d-1c23-40a6-b109-3ca8425ad623",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Trade the position monthly without any scaling\n",
    "trade_action = AddTradeAction(priceables=portfolio, trade_duration='1m', name='act')\n",
    "trade_trigger = PeriodicTrigger(\n",
    "    trigger_requirements=PeriodicTriggerRequirements(start_date=start_date, end_date=end_date, frequency='1m'),\n",
    "    actions=trade_action,\n",
    ")\n",
    "\n",
    "strategy = Strategy(None, trade_trigger)\n",
    "\n",
    "# Run backtest daily\n",
    "engine = EquityVolEngine\n",
    "backtest = engine.run_backtest(strategy, start=start_date, end=end_date)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "932678aa-cf61-4c71-b057-55a3ab81c241",
   "metadata": {},
   "outputs": [],
   "source": [
    "pnl = backtest.get_measure_series(FlowVolBacktestMeasure.PNL)\n",
    "pnl.plot(legend=True, label='PNL')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5d3c2217-f45b-4c84-a64f-afdc9e91940f",
   "metadata": {},
   "source": [
    "### Scaling quantity"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7998da4c-0a08-4698-97af-169654f1f11a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Scale the position quantity (no. of options) by 2\n",
    "trade_action_scaled = AddScaledTradeAction(\n",
    "    priceables=portfolio,\n",
    "    trade_duration='1m',\n",
    "    scaling_type=ScalingActionType.size,\n",
    "    scaling_risk=None,\n",
    "    scaling_level=2,\n",
    "    name='scaled_act',\n",
    ")\n",
    "trade_trigger_scaled = PeriodicTrigger(\n",
    "    trigger_requirements=PeriodicTriggerRequirements(start_date=start_date, end_date=end_date, frequency='1m'),\n",
    "    actions=trade_action_scaled,\n",
    ")\n",
    "\n",
    "strategy = Strategy(None, trade_trigger_scaled)\n",
    "\n",
    "# Run backtest daily\n",
    "engine = EquityVolEngine\n",
    "backtest = engine.run_backtest(strategy, start=start_date, end=end_date)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14d7e2f3-8f06-4a89-9486-9f5fb35363f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# note the performance is twice the above graph\n",
    "pnl = backtest.get_measure_series(FlowVolBacktestMeasure.PNL)\n",
    "pnl.plot(legend=True, label='PNL')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b52d3f47-ab87-4074-ae34-3ef3bb7c54c9",
   "metadata": {},
   "source": [
    "### Scaling a risk measure"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2dff6a31-583b-4858-8c7c-ef259f1a6659",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initial and final Vega of the portfolio\n",
    "with PricingContext(start_date):\n",
    "    start_vega = portfolio.calc(risk.EqVega)\n",
    "\n",
    "with PricingContext(end_date):\n",
    "    end_vega = portfolio.calc(risk.EqVega)\n",
    "\n",
    "print(start_vega.aggregate())\n",
    "print(end_vega.aggregate())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "01384407-a6c2-4083-8577-f8a98468a429",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Scale the position vega to 100\n",
    "trade_action_scaled = AddScaledTradeAction(\n",
    "    priceables=portfolio,\n",
    "    trade_duration='1m',\n",
    "    scaling_type=ScalingActionType.risk_measure,\n",
    "    scaling_risk=risk.EqVega,\n",
    "    scaling_level=100,\n",
    "    name='scaled_vega_act',\n",
    ")\n",
    "trade_trigger_scaled = PeriodicTrigger(\n",
    "    trigger_requirements=PeriodicTriggerRequirements(start_date=start_date, end_date=end_date, frequency='1m'),\n",
    "    actions=trade_action_scaled,\n",
    ")\n",
    "\n",
    "strategy = Strategy(None, trade_trigger_scaled)\n",
    "\n",
    "# Run backtest daily\n",
    "engine = EquityVolEngine\n",
    "backtest = engine.run_backtest(strategy, start=start_date, end=end_date)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10ef8a2a-b290-40dc-ad05-e070897652c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# note the scaling should be approx the 100/vega\n",
    "pnl = backtest.get_measure_series(FlowVolBacktestMeasure.PNL)\n",
    "pnl.plot(legend=True, label='PNL')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b5984b12-10ce-498a-9f78-335bd135aabe",
   "metadata": {},
   "source": [
    "### NAV Trading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "417169e2-addf-4c0b-a355-cff4f35b106a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a NAV-based action that starts with 100 available to spend\n",
    "start_date = date(2024, 1, 1)\n",
    "end_date = datetime.today().date()\n",
    "\n",
    "trade_action_scaled = EnterPositionQuantityScaledAction(\n",
    "    priceables=portfolio,\n",
    "    trade_duration='1m',\n",
    "    trade_quantity=100,\n",
    "    trade_quantity_type=BacktestTradingQuantityType.NAV,\n",
    "    name='nav_act',\n",
    ")\n",
    "trade_trigger_scaled = PeriodicTrigger(\n",
    "    trigger_requirements=PeriodicTriggerRequirements(start_date=start_date, end_date=end_date, frequency='1m'),\n",
    "    actions=trade_action_scaled,\n",
    ")\n",
    "\n",
    "strategy = Strategy(None, trade_trigger_scaled)\n",
    "\n",
    "# Run backtest daily\n",
    "engine = EquityVolEngine\n",
    "backtest = engine.run_backtest(strategy, start=start_date, end=end_date)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3832acf6-370d-4a77-ab57-219134a9ee6f",
   "metadata": {},
   "outputs": [],
   "source": [
    "pnl = backtest.get_measure_series(FlowVolBacktestMeasure.PNL)\n",
    "pnl.plot(legend=True, label='PNL')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19ba18f5-e905-4183-b47c-cd6cc7c74b0d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}